<template>
  <el-dialog
    :visible.sync="isShow"
    :title="title"
    width="392px"
    :modal-append-to-body="false"
    @close="() => resetForm()"
  >
    <el-upload
      ref="upload"
      style="width: 100%"
      :limit="1"
      accept=".xlsx, .xls"
      :action="importUrl"
      :on-change="uploadByJsqd"
      :auto-upload="false"
      :file-list="fileList"
      drag
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div class="el-upload__tip text-center" slot="tip">
        <span>仅允许导入xls、xlsx格式文件。</span>
        <el-button type="text" @click="headleDownLoad">下载模板</el-button>
        <!-- <el-button
          v-if="improtFailId && showFailButtons"
          type="text"
          @click="headleDownFailData"
          >下载导入失败数据</el-button
        > -->
      </div>
    </el-upload>
    <div slot="footer">
      <el-button
        :loading="loading"
        :disabled="loading"
        type="primary"
        @click="() => submitFileForm()"
        >确定</el-button
      >
      <el-button
        :loading="loading"
        :disabled="loading"
        @click="() => resetForm()"
        >取消</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
// import { getCookies } from "@/utils/auth";
export default {
  name: "ImportFile",
  props: {
    requestUrl: {
      type: Function,
      default: () => {},
    },
    // 列表导入地址
    importUrl: {
      type: String,
      default: "",
    },
    // 导入标题
    title: {
      type: String,
      default: "导入",
    },
    showFailButtons: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      fileList: [],
      loading: false,
      file: {},
      isShow: false,
      // 用户导入参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: {
          // Authorization: getCookies("token"),
          // 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOiJzeXNfdXNlcjoxNjY5NjI2Nzk3Mjg4ODk4NTYxIiwicm5TdHIiOiJ1THBTa2hyYnVQa2Y1MThwbzRKS2ZxYkhjSXpRNmpEeCIsInByb2plY3RJZCI6MTY1ODc0OTAyNzEwMTUyMzk3MCwidXNlcklkIjoxNjY5NjI2Nzk3Mjg4ODk4NTYxfQ.IwMPq8wRFraMYVxuwHi5avEUjqp9VJkSIL3NbWR4y_s token'
        },
      },
      improtFailId: null,
    };
  },
  watch: {},
  mounted() {
    // console.log(getCookies("token"), "token");
  },
  methods: {
    // 初始化弹窗
    init() {
      console.log(this.file, "file");
      this.isShow = true;
    },
    //文件校验方法
    beforeAvatarUpload(file) {
      console.log(file, "file");
      // 通过split方法和fileArr方法获取到文件的后缀名
      let fileArr = file.name.split(".");
      let suffix = fileArr[fileArr.length - 1];
      //只能导入.xls和.xlsx文件
      if (!/(xls|xlsx)/i.test(suffix)) {
        this.$message("文件格式不正确");
        this.fileList = [];
        return false;
      }
      //不能导入大小超过2Mb的文件
      // if (file.size > 2 * 1024 * 1024) {
      //   this.$message('文件过大，请上传小于2MB的文件〜')
      //   return false
      // }
      return true;
    },
    //文件发生改变就会触发的事件
    uploadByJsqd(file) {
      //判断是否符合beforeAvatarUpload方法中的条件
      if (this.beforeAvatarUpload(file)) {
        this.file = { ...file };
      }
    },
    // 提交上传文件
    submitFileForm() {
      this.loading = true;
      var formdata = new FormData();
      formdata.append("file", this.file.raw);
      if (!this.file.raw) {
        this.$message({
          message: "未选择文件！",
          type: "error",
        });
        this.loading = false;
        return;
      }
      //importDevice：请求接口 formdata：传递参数
      this.requestUrl(formdata)
        .then((res) => {
          console.log(res, "上传");
          // 导入存在失败
          if (res.data?.id) {
            this.improtFailId = res.data.id;
            this.$message({
              message: res.data?.msg || res.msg,
              dangerouslyUseHTMLString: true,
              type: "error",
            });
            this.$emit("clickConfirm", res.data.id, res.data);
          } else {
            this.improtFailId = null;
            this.$message({
              message: res.data?.msg || res.msg,
              dangerouslyUseHTMLString: true,
              type: "success",
            });
            this.$emit("clickConfirm");
            this.resetForm();
          }
          this.loading = false;
        })
        .catch((err) => {
          // console.log("上传失败", err);
          // this.$message({
          //   message: res.msg,
          //   dangerouslyUseHTMLString: true,
          //   type: "error",
          // });
          this.improtFailId = null;
          this.file = {};
          this.$refs.upload.clearFiles();
          this.$emit("clickConfirm", true);
          this.loading = false;
        });
    },
    // 下载模板
    headleDownLoad() {
      this.$emit("headleDownLoad");
    },
    // 下载上传失败数据
    headleDownFailData() {
      this.$emit("headleFailData", this.improtFailId);
    },
    // 关闭弹窗并重置表单
    resetForm() {
      this.isShow = false;
      console.log(12);
      this.improtFailId = null;
      (this.file = {}), this.$refs.upload.clearFiles();
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-dialog__header {
  padding: 16px 24px;
  height: 54px;
  background: #ffffff;
  border-radius: 2px 2px 0px 0px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
  .el-dialog__title {
    font-size: 16px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: rgba(0, 0, 0, 0.85);
  }
  .el-dialog__headerbtn {
    width: 16px;
    height: 16px;
  }
  .el-dialog__headerbtn .el-dialog__close {
    color: rgba(0, 0, 0, 0.45);
    font-size: 20px;
  }
}
::v-deep .el-dialog__body {
  padding: 16px;
}
::v-deep .el-dialog__footer {
  height: 64px;
  background: #ffffff;
  padding: 16px 24px;
  border-radius: 0px 0px 2px 2px;
  border-top: 1px solid rgba(0, 0, 0, 0.06);
}
.el-button {
  width: 72px;
  height: 32px;
  border-radius: 2px;
  text-align: center;
  padding: 6px 12px;
  font-size: 12px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
}
// .el-button--primary {
//   color: #ffffff;
// }
::v-deep .custom_dialog {
  margin-top: 8vh !important;
  height: 86%;
  display: flex;
  flex-direction: column;
  .el-dialog__body {
    flex: 1;
    overflow: auto;
  }
}
</style>
